/**
 * @file RoleManagement.jsx
 * @description 后台管理系统的角色管理页面组件
 */
import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { 
  Table, Card, Typography, Space, Button, Tag, Modal, 
  Form, Input, Drawer, Descriptions, Divider, Checkbox, Row, Col, App as AntdAppHook // 导入 App
} from 'antd';
import { 
  ReloadOutlined, EyeOutlined, EditOutlined, 
  PlusOutlined, DeleteOutlined 
} from '@ant-design/icons';
import { fetchAllRoles, addRole, updateRole, deleteRole } from '../store/usersSlice';
import toast from 'react-hot-toast';

const { Title } = Typography;

// 可用权限列表
const availablePermissions = [
  { id: 'all', name: '所有权限' },
  { id: 'dashboard', name: '控制面板' },
  { id: 'orders', name: '订单管理' },
  { id: 'users', name: '用户管理' },
  { id: 'roles', name: '角色管理' },
  { id: 'products', name: '商品管理' },
  { id: 'view_users', name: '查看用户' },
  { id: 'edit_users', name: '编辑用户' },
  { id: 'view_orders', name: '查看订单' },
  { id: 'edit_orders', name: '编辑订单' },
];

const RoleManagement = () => {
  const dispatch = useDispatch();
  const { roles, isLoading } = useSelector((state) => state.users);
  const [viewRole, setViewRole] = useState(null);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [currentRole, setCurrentRole] = useState(null);
  const [editForm] = Form.useForm();
  const [addForm] = Form.useForm();
  const { modal } = AntdAppHook.useApp(); // 获取 modal 实例

  useEffect(() => {
    dispatch(fetchAllRoles());
  }, [dispatch]);

  const handleRefresh = () => {
    dispatch(fetchAllRoles());
    toast.success('角色数据已刷新');
  };

  const showRoleDetails = (role) => {
    setViewRole(role);
    setDrawerVisible(true);
  };

  const closeDrawer = () => {
    setDrawerVisible(false);
  };

  const showEditModal = (role) => {
    setCurrentRole(role);
    editForm.setFieldsValue({
      name: role.name,
      description: role.description,
      permissions: role.permissions,
    });
    setEditModalVisible(true);
  };

  const handleEditCancel = () => {
    setEditModalVisible(false);
    setCurrentRole(null);
    editForm.resetFields();
  };

  const handleEditSubmit = async () => {
    try {
      const values = await editForm.validateFields();
      
      if (values.permissions.includes('all')) {
        values.permissions = ['all'];
      }
      
      dispatch(updateRole({
        id: currentRole.id,
        name: values.name,
        description: values.description,
        permissions: values.permissions,
      }));
      
      toast.success(`角色 ${values.name} 已更新`);
      setEditModalVisible(false);
      setCurrentRole(null);
      editForm.resetFields();
    } catch (error) {
      console.error('表单验证或更新失败:', error);
    }
  };

  const showAddModal = () => {
    setAddModalVisible(true);
  };

  const handleAddCancel = () => {
    setAddModalVisible(false);
    addForm.resetFields();
  };

  const handleAddSubmit = async () => {
    try {
      const values = await addForm.validateFields();
      
      const nameExists = roles.some(role => role.name === values.name);
      if (nameExists) {
        toast.error('角色名已存在，请使用其他名称');
        return;
      }
      
      if (values.permissions.includes('all')) {
        values.permissions = ['all'];
      }
      
      const newRole = {
        id: Date.now(), 
        name: values.name,
        description: values.description,
        permissions: values.permissions,
        createdAt: new Date().toISOString(),
      };
      
      dispatch(addRole(newRole));
      toast.success(`角色 ${values.name} 已创建`);
      setAddModalVisible(false);
      addForm.resetFields();
    } catch (error) {
      console.error('表单验证或添加失败:', error);
    }
  };

  const handleDeleteRole = (role) => {
    console.log('Attempting to delete role:', role); 
    if (role.name === '超级管理员') {
      toast.error('不能删除超级管理员角色');
      return;
    }
    
    modal.confirm({ // 使用从 hook 获取的 modal 实例
      title: '确认删除',
      content: `确定要删除角色 ${role.name} 吗？此操作不可撤销，且可能影响已分配此角色的用户。`,
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        dispatch(deleteRole(role.id));
        toast.success(`角色 ${role.name} 已删除`);
      },
    });
  };

  const PermissionSelector = ({ value = [], onChange }) => {
    const [selectedPermissions, setSelectedPermissions] = useState(value);
    
    const handlePermissionChange = (checkedValues) => {
      if (checkedValues.includes('all') && !selectedPermissions.includes('all')) {
        setSelectedPermissions(['all']);
        onChange(['all']);
        return;
      }
      
      if (!checkedValues.includes('all') && selectedPermissions.includes('all')) {
        setSelectedPermissions([]);
        onChange([]);
        return;
      }
      
      setSelectedPermissions(checkedValues);
      onChange(checkedValues);
    };
    
    return (
      <Checkbox.Group value={selectedPermissions} onChange={handlePermissionChange}>
        <Row>
          {availablePermissions.map(permission => (
            <Col span={8} key={permission.id}>
              <Checkbox value={permission.id}>{permission.name}</Checkbox>
            </Col>
          ))}
        </Row>
      </Checkbox.Group>
    );
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '权限数量',
      key: 'permissionCount',
      render: (_, record) => {
        if (record.permissions.includes('all')) {
          return <Tag color="gold">所有权限</Tag>;
        }
        return <Tag color="blue">{record.permissions.length}</Tag>;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date) => date ? new Date(date).toLocaleDateString('zh-CN') : '-',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="text" 
            icon={<EyeOutlined />} 
            onClick={() => showRoleDetails(record)}
          >
            查看
          </Button>
          <Button 
            type="text" 
            icon={<EditOutlined />} 
            onClick={() => showEditModal(record)}
          >
            编辑
          </Button>
          <Button 
            type="text" 
            danger
            icon={<DeleteOutlined />} 
            onClick={() => handleDeleteRole(record)}
            disabled={record.name === '超级管理员'}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Title level={2}>角色管理</Title>
      
      <Card style={{ marginBottom: 16 }}>
        <Space style={{ marginBottom: 16 }}>
          <Button 
            type="primary" 
            icon={<ReloadOutlined />} 
            onClick={handleRefresh}
          >
            刷新
          </Button>
          <Button 
            type="primary" 
            icon={<PlusOutlined />} 
            onClick={showAddModal}
          >
            添加角色
          </Button>
        </Space>
        
        <Table 
          columns={columns} 
          dataSource={roles.map(role => ({ ...role, key: role.id }))} 
          loading={isLoading}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      <Drawer
        title="角色详情"
        placement="right"
        width={500}
        onClose={closeDrawer}
        open={drawerVisible}
      >
        {viewRole && (
          <>
            <Descriptions bordered column={1}>
              <Descriptions.Item label="角色ID">{viewRole.id}</Descriptions.Item>
              <Descriptions.Item label="角色名称">{viewRole.name}</Descriptions.Item>
              <Descriptions.Item label="描述">{viewRole.description}</Descriptions.Item>
              <Descriptions.Item label="创建时间">
                {viewRole.createdAt ? new Date(viewRole.createdAt).toLocaleString('zh-CN') : '-'}
              </Descriptions.Item>
            </Descriptions>

            <Divider orientation="left">权限列表</Divider>
            <div style={{ padding: '8px 0' }}>
              {viewRole.permissions.includes('all') ? (
                <Tag color="gold" style={{ margin: '4px' }}>所有权限</Tag>
              ) : (
                viewRole.permissions.map(perm => {
                  const permInfo = availablePermissions.find(p => p.id === perm);
                  return (
                    <Tag key={perm} color="green" style={{ margin: '4px' }}>
                      {permInfo ? permInfo.name : perm}
                    </Tag>
                  );
                })
              )}
            </div>
          </>
        )}
      </Drawer>

      <Modal
        title="编辑角色"
        open={editModalVisible}
        onCancel={handleEditCancel}
        footer={[
          <Button key="cancel" onClick={handleEditCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleEditSubmit}>
            保存
          </Button>,
        ]}
        width={700}
      >
        {currentRole && (
          <Form form={editForm} layout="vertical">
            <Form.Item
              name="name"
              label="角色名称"
              rules={[{ required: true, message: '请输入角色名称' }]}
            >
              <Input placeholder="请输入角色名称" disabled={currentRole.name === '超级管理员'} />
            </Form.Item>
            <Form.Item
              name="description"
              label="角色描述"
              rules={[{ required: true, message: '请输入角色描述' }]}
            >
              <Input.TextArea rows={2} placeholder="请输入角色描述" />
            </Form.Item>
            <Form.Item
              name="permissions"
              label="角色权限"
              rules={[{ required: true, message: '请选择至少一个权限' }]}
            >
              <PermissionSelector />
            </Form.Item>
          </Form>
        )}
      </Modal>

      <Modal
        title="添加角色"
        open={addModalVisible}
        onCancel={handleAddCancel}
        footer={[
          <Button key="cancel" onClick={handleAddCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleAddSubmit}>
            创建
          </Button>,
        ]}
        width={700}
      >
        <Form form={addForm} layout="vertical">
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>
          <Form.Item
            name="description"
            label="角色描述"
            rules={[{ required: true, message: '请输入角色描述' }]}
          >
            <Input.TextArea rows={2} placeholder="请输入角色描述" />
          </Form.Item>
          <Form.Item
            name="permissions"
            label="角色权限"
            rules={[{ required: true, message: '请选择至少一个权限' }]}
          >
            <PermissionSelector />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default RoleManagement;